/* 
 * File:   AudioSource.cpp
 * Author: RedEyedKiller
 * 
 * Created on 16 Δεκέμβριος 2010, 12:12 πμ
 */

#include "AudioSource.h"
#include "AudioCore.h"
#include <iostream>

#ifdef __WIN32
#include <al.h>
#else
#include <AL/al.h>
#endif

#include "../ResourceManager.h"

namespace al
{

AudioSource::AudioSource(ALuint rawSource,bool oneTime /*= true*/) : AbstractALSource(rawSource)
{
    this->oneTime = oneTime;
    alSource3f( sourceId, AL_POSITION, 0.0, 0.0, 0.0 );
    alSource3f( sourceId, AL_VELOCITY, 0.0, 0.0, 0.0 );
    alSource3f( sourceId, AL_DIRECTION, 0.0, 0.0, 0.0 );
    alSourcef( sourceId, AL_ROLLOFF_FACTOR, 0.0 );
    alSourcei( sourceId, AL_SOURCE_RELATIVE, AL_TRUE );

    /* Rolloff factor judges the strength of attenuation over distance.
     * By setting it to 0 we will have turned it off.
     * This means that no matter how far away the Listener is to the source
     * will still hear it.
     * The same idea applies to source relativity.
     */
    soundData = NULL;
}

AudioSource::~AudioSource()
{
    AudioCore::ClearErrorBuffer();
    
    alDeleteSources( 1, &sourceId );
    
    if( !AudioCore::Check( ) )
    {
        LOG( Logger::CHANNEL_AUDIO, LogFileStream::LEVEL_NOTE ) << "alDeleteSources failed trying to delete source ";// << SOURCE;
    }
    
    if( soundData != NULL )
    {
        soundData->DecreaseReference( );
    }
}

bool AudioSource::Load(const char* file)
{
    //if data already exists release it
    if( soundData != NULL )
    {
        soundData->DecreaseReference( );
    }
    //load sound via resource manager
    soundData = ResourceManager::GetInstance( )->GetSound( file );
    if( soundData != NULL )
    {
        AttachBuffer( soundData->GetRawData( )->GetBufferId( ) );
        return true;
    }

    return false;
}

void AudioSource::SetOneTime(bool oneTime)
{
    this->oneTime = oneTime;
}

bool AudioSource::IsOneTime() const
{
    return oneTime;
}

bool AudioSource::AttachBuffer(ALuint buffer)
{
    AudioCore::ClearErrorBuffer( );

    alSourcei( sourceId, AL_BUFFER, buffer );

    if( !AudioCore::Check( ) )
    {
        LOG( Logger::CHANNEL_AUDIO, LogFileStream::LEVEL_NOTE ) << "alSourcei failed trying to atatach buffer ";// << SOURCE;
        return false;
    }
    return true;
}


}
